package com.example.teaching_server.service;

import com.example.teaching_server.dto.TermDTO;
import com.example.teaching_server.entity.TermEntity;
import com.example.teaching_server.exception.TermNotFoundException;
import com.example.teaching_server.repository.TermRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学期管理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TermService {

    private final TermRepository termRepository;

    /**
     * 获取当前学期
     */
    public TermDTO getCurrentTerm() {
        log.debug("获取当前学期");

        return termRepository.findByIsCurrentTrue()
                .map(this::convertToDTO)
                .orElseThrow(() -> {
                    log.warn("未找到当前活动学期");
                    return new TermNotFoundException("当前未设置活动学期");
                });
    }

    /**
     * 获取所有学期（按学期ID升序排列）
     */
    public List<TermDTO> getAllTerms() {
        log.debug("获取所有学期");

        return termRepository.findAllByOrderByTermIdAsc()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据日期获取相关学期
     */
    public List<TermDTO> getTermsByDate(LocalDate date) {
        log.debug("根据日期查询学期: date={}", date);

        validateDate(date);

        return termRepository.findTermsByDate(date)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 转换学期实体为DTO
     */
    private TermDTO convertToDTO(TermEntity entity) {
        TermDTO dto = new TermDTO();
        dto.setTermId(entity.getTermId());
        dto.setTermName(entity.getTermName());
        dto.setStartDate(entity.getStartDate());
        dto.setEndDate(entity.getEndDate());
        dto.setIsCurrent(entity.getIsCurrent());
        return dto;
    }

    /**
     * 验证日期参数
     */
    private void validateDate(LocalDate date) {
        if (date == null) {
            throw new IllegalArgumentException("日期参数不能为空");
        }
    }
}
